﻿#include <QDebug>

#include "CPlcSceneView.h"

CPlcSceneView::CPlcSceneView(QWidget *parent) : QGraphicsView(parent)
{
    mScene          = NULL;
    mInit           = true;
    QScrollBar *bar = this->verticalScrollBar();
    bar->setVisible(true);
}

void CPlcSceneView::setScene(CPlcScene *scene)
{
    if (mScene != NULL) return;

    mScene = scene;
    QGraphicsView::setScene(scene);
    //添加信号关联处理:场景尺寸调整时，视窗追踪选中的元件
    connect(mScene, SIGNAL(sgnSelectItemChanged()), this, SLOT(updateView()));
}

//重新调整视窗，追踪显示选中的元件
void CPlcSceneView::updateView()
{
    if (mScene == NULL) return;
    //获取场景的最大高度
    double sceneHeight = mScene->sceneRect().height();
    double viewHeight  = this->size().height() - 2;   //去除边框的两像素
    //添加0.5误差，去除不需要调整的情况
    if ((sceneHeight - 0.5) <= viewHeight) return;
    if (mScene->getSelectItem() == NULL) return;
    QRectF rect = mScene->getSelectItem()->getRect();
    //选中元件的上、下限值
    double itemTop    = rect.top();
    double itemBottom = rect.bottom();

    QScrollBar *bar   = this->verticalScrollBar();
    double viewTop    = bar->value();
    double viewBottom = viewTop + viewHeight;

    //如果选中元件的上限小于视窗显示的上限，调整bar
    if (itemTop < viewTop) bar->setValue(itemTop);

    if (itemBottom > viewBottom) bar->setValue(itemBottom);
}

void CPlcSceneView::resizeEvent(QResizeEvent *event)
{
    CPlcScene *scene = dynamic_cast<CPlcScene *>(this->scene());
    if (scene == NULL)
    {
        QGraphicsView::resizeEvent(event);
        return;
    }

    if (mInit)
    {
        //设置显示为起始顶上位置
        double width = this->size().width() - verticalScrollBar()->width() - 2;
        double high  = this->size().height() - 2;
        mScene->setSceneRect(QRectF(0, 0, width, high));
        centerOn(100, 100);
        mInit = false;
    }

    QScrollBar *bar = this->verticalScrollBar();
    QSize size      = event->size();
    double width    = size.width() - bar->width() - 2;
    scene->updateSceneWidth(width);   //重新调整场景宽度

    //执行系统默认事件
    QGraphicsView::resizeEvent(event);

    updateView();

    if (mInit)
    {
        //设置显示为起始顶上位置
        centerOn(100, 100);
        mInit = false;
    }
}
